﻿using DevExpress.XtraEditors.Repository;
using EyFramework.Common;
using EyFramework.Library;
using EyFramework.Sys.Core;
using Ncov2019.Core.Service;
using Ncov2019.Entity;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Ncov2019
{
    public partial class FrmNcovPatSelect : FrmDevBase
    {
        private List<GridColumnInfo> columnInfos = new List<GridColumnInfo>();

        private INcovUsersService ncovUsersService;

        private INcovOrderRecordService ncovOrderRecordService;

        private long _Record_seq;

        private List<long> _PatSeqList;

        public FrmNcovPatSelect(long record_seq)
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            _Record_seq = record_seq;
        }

        private void InitForm()
        {
            DataBinder.BindingLookupEditDataSource(lueRylb, SysCache.GetCacheSysDict("ncov_pat_type"), "DICT_LABEL", "DICT_LABEL");
            gvData.ShowRowNum();
            #region
            var col = new GridColumnInfo("ISCHECK", "选择", 50);
            RepositoryItemCheckEdit rice = new RepositoryItemCheckEdit();
            rice.CheckedChanged += Rice_CheckedChanged;
            col.Columnedit = rice;
            col.COL_READONLY = false;
            columnInfos.Add(col);
            columnInfos.Add(new GridColumnInfo("CHT_ID", "病历号码", 100));
            columnInfos.Add(new GridColumnInfo("PAT_NM", "姓名", 100));
            columnInfos.Add(new GridColumnInfo("BIRTHDAY", "出生日期", 100));
            columnInfos.Add(new GridColumnInfo("SEX", "性别", 50));
            columnInfos.Add(new GridColumnInfo("ID_NO", "身份证号", 200));
            columnInfos.Add(new GridColumnInfo("TELPHONE", "联系电话", 100));
            columnInfos.Add(new GridColumnInfo("COMPANY", "单位名称", 200));
            columnInfos.Add(new GridColumnInfo("DEPARTMENT", "部门名称", 200));
            columnInfos.Add(new GridColumnInfo("PAT_TYPE", "人员类型", 100));
            columnInfos.Add(new GridColumnInfo("PAT_TAGS", "人员标记", 200));
            #endregion
            DevExpress.XtraGrid.GridFormatRule gfrId = new DevExpress.XtraGrid.GridFormatRule() { Name = "gfrId" };
            // 指定应用到编号列
            gfrId.Column = gvData.Columns["ISADD"];
            gfrId.Rule = new DevExpress.XtraEditors.FormatConditionRuleExpression()
            {
                // 使用Dev默认提供的预定义样式
                Expression = "[ISADD]=true ", // Id值为奇数
            };
            // 是否应用到整行
            gfrId.ApplyToRow = true;
            this.gvData.FormatRules.Add(gfrId);
        }

        private void Rice_CheckedChanged(object sender, EventArgs e)
        {
            if (!gvData.IsNewItemRow(gvData.FocusedRowHandle))
            {
                gvData.CloseEditor();
                gvData.UpdateCurrentRow();
            }
        }

        private void FrmNcovLabCollect_Load(object sender, EventArgs e)
        {
            ncovUsersService = EyFramework.Common.Globals.GetService<INcovUsersService>();
            ncovOrderRecordService = EyFramework.Common.Globals.GetService<INcovOrderRecordService>();
            InitForm();
            QueryHasImport(_Record_seq);
            QueryData();
        }

        private void QueryHasImport(long record_seq)
        {
            //查询以及导入到本次开单记录的人员
            _PatSeqList = ncovOrderRecordService.QueryHasImport(record_seq);
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            ShowLoading();
            btnQuery.Enabled = false;
            try
            {
                QueryData();
                //避免多次重复点击按钮触发多次查询检索,清理掉windows的事件消息
                Application.DoEvents();
                CloseLoading();
                btnQuery.Enabled = true;
            }
            catch
            {
                btnQuery.Enabled = true;
                throw;
            }
        }

        private void QueryData()
        {
            var ncovUsersParam = new NcovUsersParam
            {
                CHT_ID = teChtId.Text.Trim(),
                PAT_NM = tePatNm.Text.Trim(),
                PAT_TYPE = lueRylb.EditValue == null ? "" : SysCache.GetDictValue(lueRylb.EditValue.ToString(), "ncov_pat_type"),
                DC_FLAG = chkDcFlag.Checked ? "Y" : "N"
            };
            List<NcovUsersDto> ncovUsers = ncovUsersService.QueryBy(ncovUsersParam);
            ncovUsers.ForEach(p =>
            {
                p.ISCHECK = false;
                p.SEX = SysCache.GetDictVal(p.SEX, SysConstants.DICT_SEX);
                p.PAT_TYPE = SysCache.GetDictVal(p.PAT_TYPE, SysConstants.DICT_NCOV_PAT_TYPE);
                p.ISADD = _PatSeqList.Contains(p.PAT_SEQ);
            });
            gcData.DataSource = ncovUsers;
            DevPublic.SetGridControlView(gvData, columnInfos, true, true);
        }

        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < gvData.RowCount; i++)
            {
                //就用这条语句虽然能直接将界面上的打上勾，但是如果该列正好是排序状态下，行顺序会立即调整，导致此循环混乱
                //所以改用下面两句取出实体，给实体赋值。最后再gdcPassbyArl.RefreshDataSource()更新界面。
                //gdvPassbyArl.SetRowCellValue(i, "选择", checkEdit1.Checked);
                NcovUsersDto arl = gvData.GetRow(i) as NcovUsersDto;
                arl.ISCHECK = chkAll.Checked;
            }
            gvData.RefreshData();
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            List<NcovUsersDto> addUsers = new List<NcovUsersDto>();
            for (int i = 0; i < gvData.RowCount; i++)
            {
                NcovUsersDto arl = gvData.GetRow(i) as NcovUsersDto;
                if (arl.ISCHECK && !arl.ISADD)
                {
                    addUsers.Add(arl);
                }
            }
            if (addUsers.Count == 0)
            {
                Globals.ShowError("您没有选中需要导入的核酸检测对象！");
                return;
            }
            AddNcovUsers(addUsers);
        }

        /// <summary>
        /// 将核酸检测对象导入到检测记录中
        /// </summary>
        /// <param name="ncovUsers"></param>
        private void AddNcovUsers(List<NcovUsersDto> ncovUsers)
        {
            if (ncovOrderRecordService.AddNcovUsers(_Record_seq, ncovUsers))
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
    }
}